import dayjs from "dayjs";
// import { request } from "../../request/request";
const util = require("../../../utils/util");
// 获取应用实例
const app = getApp();

// 初始化数据库
const db = wx.cloud.database();
const uimg = db.collection("uimg");

// pages/score/score.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    theme: 1,
    shengyu: 0,
    isLoading: false,
    openid: "",
    o_openid: "",
    scoreList: [],
    ownNum: 0,
    otherNum: 0,
    ownScore: [],
    otherScore: [],
    _scoreCause: "",
    _score: "",
    heartbeat_value: 0,

    navHeight: app.globalData.navBarHeight,
    menuHeight: app.globalData.menuHeight,
    menuRight: app.globalData.menuRight,
    menuTop: app.globalData.menuTop,
  },

  // 获取数据
  getScoreData(openid) {
    const that = this;
    const { o_openid } = that.data;
    if (!o_openid) {
      wx.showModal({
        title: "绑定提醒",
        content: "你还没有绑定情侣，是否现在去绑定？",
        complete: (res) => {
          if (res.cancel) {
            wx.navigateBack();
          }
          if (res.confirm) {
            wx.navigateTo({
              url: "/packageMine/pages/invitecode/invitecode",
            });
          }
        },
      });
      return;
    }

    wx.showLoading({
      title: "Loading...",
    });
    let { ownScore, otherScore, ownNum, otherNum } = that.data;
    uimg.where({ _openid: openid }).get({
      success: (res) => {
        let { score, heartbeat_value } = res.data[0];
        that.setData({ heartbeat_value });
        if (score) {
          ownScore = score.filter((i) => i.openid == openid);
          otherScore = score.filter((i) => i.openid != openid);

          if (ownScore.length != 0 && otherScore.length != 0) {
            otherNum = ownScore[0].shengyu;
            ownNum = otherScore[0].shengyu;
          } else if (ownScore.length != 0 && otherScore.length == 0) {
            otherNum = ownScore[0].shengyu;
            ownNum = 0;
          } else if (ownScore.length == 0 && otherScore.length != 0) {
            otherNum = 0;
            ownNum = otherScore[0].shengyu;
          } else {
            otherNum = 0;
            ownNum = 0;
          }

          that.setData({
            scoreList: score,
            ownNum,
            otherNum,
            isLoading: false,
          });
        } else {
          that.setData({
            scoreList: [],
            ownNum: 0,
            otherNum: 0,
            isLoading: false,
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: "获取失败",
          icon: "none",
        });
      },
      complete: () => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        that.setData({
          isLoading: false,
        });
      },
    });
  },

  getScoreCause(e) {
    let { _scoreCause } = this.data;
    _scoreCause = e.detail.value;
    this.setData({
      _scoreCause,
    });
  },

  getScore(e) {
    let { _score } = this.data;
    _score = e.detail.value;
    this.setData({
      _score,
    });
  },

  handleScore(e) {
    const that = this;
    const { type } = e.currentTarget.dataset;
    let { openid, o_openid, scoreList, _scoreCause, _score, otherNum, heartbeat_value } =
      that.data;
    if (_scoreCause.trim() == "" || _score.trim() == "") {
      wx.showModal({
        title: "提示",
        content: "请检查原因和分数是否完整",
      });
      return;
    }
    if (type == "add") {
      scoreList.unshift({
        cause: _scoreCause,
        score: _score,
        state: true,
        time: dayjs(new Date()).format("YYYY/MM/DD HH:mm:ss"),
        shengyu: JSON.parse(JSON.stringify(Number(otherNum) + Number(_score))),
        openid,
        scoreType: type,
      });
    } else if (type == "minus") {
      scoreList.unshift({
        cause: _scoreCause,
        score: _score,
        state: true,
        time: dayjs(new Date()).format("YYYY/MM/DD HH:mm:ss"),
        shengyu: JSON.parse(JSON.stringify(Number(otherNum) - Number(_score))),
        openid,
        scoreType: type,
      });
    }

    heartbeat_value += 1;
    that.setData({ heartbeat_value });

    uimg.where({ _openid: openid }).update({
      data: {
        score: scoreList,
        heartbeat_value
      },
      success: () => {
        uimg.where({ _openid: o_openid }).update({
          data: {
            score: scoreList,
          },
          success: () => {
            that.setData({
              _scoreCause: "",
              _score: "",
            });
            that.getScoreData(openid);
          },
          complete: () => { },
        });
      },
      fail: () => {
        that.setData({
          _scoreCause: "",
          _score: "",
        });
        that.getScoreData(openid);
      },
    });

    util.subscribe(1, '“计分器”所增加心动值', false);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const openid = wx.getStorageSync("openid");
    const o_openid = wx.getStorageSync("o_openid");
    this.setData({
      theme: app.globalData.theme,
      openid,
      o_openid,
    });
    this.getScoreData(openid);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const { openid } = this.data;
    this.setData({
      isLoading: true,
    });
    wx.showLoading({
      title: "Loading...",
    });
    this.getScoreData(openid);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
